<!--created by yuyupeng-->
<!--2023/12/08-->
<!-- 定义主子表关联关系 -->
<template>
  <div>
    <a-steps changeable :current="current" @change="setCurrent">
      <a-step>选择主表</a-step>
      <a-step>定义主子表关联关系</a-step>
    </a-steps>
    <div
      :style="{
        width: '100%',
        height: '300px',
        overflowY: 'auto',
        textAlign: 'center',
      }"
    >
      <div v-if="current === 1">
        <a-result :status="null">
          <template #title>
            <a-space>
              请选择主表：
              <a-radio-group v-model="mainTableName" :options="tableNameList" />
            </a-space>
          </template>
        </a-result>
      </div>
      <div v-else-if="current === 2">
        <!--表格：表字段-->
        <a-table
          :columns="tbColumn"
          :data="tbData"
          :scroll="{ y: 400 }"
          row-key="id"
          :pagination="false"
        >
          <!--插槽（通用）：普通输入框-->
          <template #inputBox="{ rowIndex, column }">
            <a-input
              v-model="tbData[rowIndex][column.dataIndex]"
              :disabled="tbData[rowIndex].disabled"
            />
          </template>

          <!--插槽：主表关联字段名-->
          <template #joinKeySelect="{ rowIndex, column }">
            <a-select
              v-model="tbData[rowIndex][column.dataIndex]"
              :disabled="tbData[rowIndex].disabled"
              :options="columnKeySelectOptions(tbData[rowIndex].joinTable)"
            />
          </template>

          <!--插槽：子表关联字段名-->
          <template #curKeySelect="{ rowIndex, column }">
            <a-select
              v-model="tbData[rowIndex][column.dataIndex]"
              :disabled="tbData[rowIndex].disabled"
              :options="columnKeySelectOptions(tbData[rowIndex].curTable)"
            />
          </template>
        </a-table>
      </div>
    </div>
    <a-space size="large">
      <a-button type="primary" :disabled="current <= 1" @click="onPrev">
        <IconLeft /> 上一步
      </a-button>
      <a-button type="primary" :disabled="current >= 2" @click="onNext">
        下一步 <IconRight />
      </a-button>
    </a-space>
  </div>
</template>

<!--新script-->
<script lang="ts" setup>
  import { defineExpose, ref, toRefs } from 'vue';
  import { Notification, TableColumnData } from '@arco-design/web-vue';
  import { getDbTableColumns } from '@/api/infrastructure/business-entity';

  /**
   * data
   */
  const props = defineProps({
    dataSourceId: {
      // 数据源Id
      type: String,
      required: true,
    },
    tableNameList: {
      // 数据库表名List
      type: Array,
      required: true,
    },
  });
  const { dataSourceId, tableNameList } = toRefs(props); // 根据props创建多个 ref 对象
  const current = ref<number>(1);
  const mainTableName = ref<string>(tableNameList?.value[0] as string); // 主表名称
  const tbColumn: TableColumnData[] = [
    {
      title: '序号',
      dataIndex: 'index',
      width: 60,
      fixed: 'left',
      render: ({ rowIndex }) => rowIndex + 1,
    },
    {
      title: '主表',
      dataIndex: 'joinTable',
      width: 150,
    },
    {
      title: '主表关联字段',
      dataIndex: 'joinKey',
      width: 150,
      slotName: 'joinKeySelect',
    },
    {
      title: '子表',
      dataIndex: 'curTable',
      width: 150,
    },
    {
      title: '子表关联字段',
      dataIndex: 'curKey',
      slotName: 'curKeySelect',
      width: 150,
    },
  ];
  const tbData = ref<any[]>([]);
  const tableColumnList = ref<any[]>([]);
  const onPrev = () => {
    current.value = Math.max(1, current.value - 1);
  };
  const onNext = () => {
    if (mainTableName.value) {
      tbData.value = [];
      tableNameList?.value.forEach((item) => {
        if (item !== mainTableName.value) {
          tbData.value.push({
            joinTable: mainTableName.value,
            joinKey: '',
            curTable: item,
            curKey: '',
          });
        }
      });
      getColumnKeySelectOptions();
      current.value = Math.min(3, current.value + 1);
    } else {
      Notification.warning({
        content: '请选择主表！',
      });
    }
  };
  const setCurrent = (val: number) => {
    current.value = val;
  };
  /**
   * @description 根据表名生成对应的表字段下拉框数据源
   * @param tableName
   */
  const columnKeySelectOptions = (tableName: string) => {
    const selectOptions = [] as any[];
    tableColumnList.value.forEach((item: any) => {
      if (item.tableName === tableName) {
        selectOptions.push({
          label: item.name,
          value: item.name,
        });
      }
    });
    return selectOptions;
  };
  /**
   * @description 获取主子表关联表格数据
   */
  const getAssociationTableList = () => {
    return tbData.value;
  };
  /**
   * @description 获取主表名称
   */
  const getMainTableName = () => {
    return mainTableName.value;
  };
  /**
   * @description 获取表格字段下拉框数据源
   */
  const getColumnKeySelectOptions = () => {
    tableColumnList.value = [];
    tableNameList?.value.forEach(async (item) => {
      const { data } = await getDbTableColumns(dataSourceId.value, item);
      data.forEach((e: any) => {
        e.tableName = item;
        tableColumnList.value.push(e);
      });
    });
  };
  defineExpose({ getAssociationTableList, getMainTableName }); // 在<srcipt setup>的写法中，想要子组件中的方法可以被父组件调用，要通过defineExpose将方法暴露出去
</script>

<style lang="less" scoped></style>
